package com.gitee.shigen.config;

import com.gitee.shigen.enums.DBTypeEnum;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;

/**
 * 通过ThreadLocal将数据源设置到每个线程上下文
 *
 * @author shigenfu
 */
@Slf4j
public class DataSourceContextHolder {

    private static final ThreadLocal<DBTypeEnum> CONTEXT_HOLDER = new ThreadLocal<>();

    private static final AtomicInteger COUNTER = new AtomicInteger(-1);

    public static void set(DBTypeEnum dbType) {
        CONTEXT_HOLDER.set(dbType);
    }

    public static DBTypeEnum get() {
        return CONTEXT_HOLDER.get();
    }

    public static void clear() {
        CONTEXT_HOLDER.remove();
    }

    public static void master() {
        set(DBTypeEnum.MASTER);
        log.info("切换到master");
    }

    public static void slave() {
        //  轮询
        if (COUNTER.get() > 9999) {
            COUNTER.set(-1);
        }
        set(DBTypeEnum.SLAVE1);
        log.info("切换到slave1");
    }

}
